package cn.idu.ismik.sample.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 通过反射创建对象
 */
public class Test09 {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class c1 = Class.forName("cn.idu.ismik.sample.reflection.User");

        User u1 = (User) c1.newInstance();//调用类的无参构造器
        System.out.println(u1);

        //通过构造器创建对象
        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user2 = (User) constructor.newInstance("ddd", 001, 18);
        System.out.println(user2);

        //通过反射调用普通方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        setName.invoke(user2, "dou");
        System.out.println(user2);

        //通过反射修改属性
        Field name = c1.getDeclaredField("name");
        name.setAccessible(true);//启用可见性，不能直接操作私有属性
        name.set(user2, "dou2");
        System.out.println(user2);
    }
}
